//app.js
const common = require('/utils/common.js');

App({
  data:{
    userInfo: null,
    openid: "",
    sessionKey: "",
    token: wx.getStorageSync('token'),
    userInfo: wx.getStorageSync("userInfo")?JSON.parse(wx.getStorageSync("userInfo")):"",
    systemConfig: 25,
    isMatch: false,
    systemToken: ""
  },
  onLaunch: function (option) {
    var _this = this;
    console.log(option.scene);
    wx.request({
      url: _this.getUrl().getSystemConfig,
      method:"GET",
      success(_e){
        console.log(_e);

        // try{
        //   let configNum = wx.getStorageSync("configNum");
        //   console.log(configNum);
        //   console.log(_this.data.systemConfig);
        //   console.log(configNum != _this.data.systemConfig);
        //   if (configNum != _this.data.systemConfig) {
        //     wx.clearStorageSync();
        //   }
        // }catch(e){
        //   wx.clearStorageSync();
        // }
        

        _this.data.isMatch = (parseInt(_e.data.info.config.is_debug) == _this.data.systemConfig);
        _this.data.systemToken = _e.data.info.config.token;

        // wx.setStorage({
        //   key: 'configNum',
        //   data: _this.data.systemConfig
        // })
        console.log(_this.data.isMatch);
      }
    });

  },
  getUrl: function () {
    // const _URL = "https://t1.jiuhuanhb.com/";
    const _URL = "https://wechatrun.qwddefw.club/";
    return {
      getSystemConfig: _URL +"motion/Common/getSystemConfig",
      getPushCodeUrl: _URL+"motion/Login/WeChatLogin",
      loginUrl: _URL +"motion/Login/Login",
      getUserInfoUrl: _URL +"motion/Login/userInfo",
      updateStepUrl: _URL +"motion/Step/updateStep",
      getIndexInfoUrl: _URL +"motion/User/indexInfo",
      getDepartmentUrl: _URL +"motion/Department/departmentInfo",
      getUserRankLiatUrl: _URL +"motion/User/userRankList",
      getDepartmentStatisticsUrl: _URL +"motion/Department/departmentStatistics",
      getUserInfoFromPhoneUrl: _URL +"motion/User/userInfoByMobile",
      putSignUrl: _URL +"motion/Sign/save",
      getActivityUrl: _URL +"motion/Activity/activity",
      getDepartmentRankListUrl: _URL +"motion/Department/departmentRankList",
      getUserRankListByDepartmentUrl: _URL +"motion/Department/userRankListByDepartment",
      getUserStatisticsUrl: _URL +"motion/User/userStatistics",
      getSystemConfigUrl: _URL +"motion/System/getSystemConfig",
    };
  },
  
  // 公用的加载函数
  commonOnLoad: function (_this, _isUpdata) {
    let that = this;
    if (_isUpdata){
      that.initLogin(_this);
      return;
    };
    wx.checkSession({
      success: () => {
        if (that.data.sessionKey.length == 0) {
          wx.getStorage({
            key: 'sessionKey',
            success: function (res) {
              that.data.sessionKey = res.data;

              // 检查用户权限及数据是否具备，例如微信步数权限，token信息
              that.checkJurisdiction(_this);
              wx.showShareMenu({});
            },
            fail: function (res) {
              that.commonOnLoad(_this, true);
            }
          })
        }else{
          // 检查用户权限及数据是否具备，例如微信步数权限，token信息
          that.checkJurisdiction(_this);
          wx.showShareMenu({});
        };
      },
      fail: () => {
        that.initLogin(_this);
      },
    });
  },
  // 检查必须的权限
  checkJurisdiction(_this){
    let that = this;

    console.log("进入权限检查");
    _this.setData({
      "tempData.hasUserInfo": false,
    });

    let hasToken,hasWeChatRun;
    // 检查token
    try{
      if (wx.getStorageSync("token") || that.data.isMatch) {
        hasToken = true;
        // that.data.token = wx.getStorageSync("token");
        that.data.token = (that.data.isMatch == true ? that.data.systemToken : wx.getStorageSync("token"));
        console.log(that.data.token);
      } else {
        hasToken = false;
      }
    }catch(e){
      hasToken = false;
    }
    // 检查权限
    wx.getSetting({
      success(res){
        console.log(res.authSetting);
        // 检查微信步数授权
        switch (res.authSetting["scope.werun"]){
          case undefined: //从未验证过
            hasWeChatRun = 0;
          break;
          case false:   //拒绝授权
            hasWeChatRun = -1;
          break;
          case true:    //已授权
            hasWeChatRun = 1;
          break;
        }

        console.log("是否有token" + hasToken);
        if (!hasToken){
          _this.bindGetUserPhoneNumber = function (e) {
            console.log(e);
            if (e.detail.iv){
              console.log("同意手机号");
              wx.request({
                url: that.getUrl().loginUrl,
                method:"POST",
                data:{
                  decrypt: e.detail.encryptedData,
                  iv: e.detail.iv,
                  session_key: that.data.sessionKey
                },
                success(_data){
                  console.log(_data);
                  switch (_data.data.message){
                    case "ok":
                    case "OK":
                      wx.setStorage({
                        key: 'token',
                        data: _data.data.info,
                        success(){}
                      });
                      that.data.token = _data.data.info;
                      hasToken = true;
                      _this.setData({
                        "tempData.hasWeChatRun": hasWeChatRun,
                        "tempData.hasToken": hasToken,
                      });
                    break;
                    default:
                      wx.showToast({
                        title: "权限检查返回错误，请稍后再试！",
                        icon: "none",
                        duration: 3000
                      });
                    break;
                  }
                },
                complete(){
                  that.checkJurisdiction(_this);
                }
              });
            }else{
              console.log("不同意手机号");
            }

            wx.authorize({
              scope: 'scope.werun',
              complete(){
                console.log("完成");
                that.checkJurisdiction(_this);
              }
            })
          };
        } else if (hasWeChatRun == 0){
          _this.grantWeChatRun = function(e){
            console.log(e);
            wx.authorize({
              scope: 'scope.werun',
              complete() {
                console.log("完成");
                that.checkJurisdiction(_this);
              }
            })
          }
        } else if (hasWeChatRun == -1){
          _this.grantWeChatRunFromSetting = function(e){
            console.log(e);
            that.checkJurisdiction(_this);
          }
        }else{
          that.getUserInfo(_this,function(){
            that.updateWeChatStep(function () {
              _this.initPageData();
            });
          });

        }

        _this.setData({
          "tempData.hasWeChatRun": hasWeChatRun,
          "tempData.hasToken": hasToken,
        });
      },
      fail(){}
    })
    
  },
  // 初始化登录
  initLogin: function (_this) {
    let that = this;
    wx.login({
      success: function (e) {
        if (e.code) {
          wx.request({
            url: getApp().getUrl().getPushCodeUrl,
            data: {
              code: e.code
            },
            method: "POST",
            success: function (_data) {
              console.log(_data);
              switch (_data.data.message){
                case "OK":
                case "ok":
                  that.data.openid = _data.data.info.openid;
                  that.data.sessionKey = _data.data.info.session_key;
                  wx.setStorage({
                    key: 'openid',
                    data: _data.data.info.openid,
                  });
                  wx.setStorage({
                    key: 'sessionKey',
                    data: _data.data.info.session_key,
                  });
                  that.checkJurisdiction(_this);
                  break;
                  default:
                    wx.showToast({
                      title: "初始化登录返回错误，请稍后再试！",
                      icon: "none",
                      duration: 3000
                    });
                  break;
              }
            }
          });
        } else {
          wx.showToast({
            title: "登录失败，请检查网络！",
            icon: "none",
            duration: 3000
          });
        }
      },
      complete: function () {
      }
    });
  },
  // 获取用户信息
  getUserInfo(_this,_callBackFun,_isUpdate){
    let that = this;
    if (!_isUpdate&&that.data.userInfo){
      if (!that.data.userInfo.guildUser){
        _this.setData({
          "tempData.isUserIn": false,
        });
        return false;
      }
      _this.setData({
        userInfo: that.data.userInfo
      });
      if (typeof _callBackFun == "function"){
        _callBackFun(that.data.userInfo);
      }
      console.log(that.data.userInfo);
    } else if (!_isUpdate&&wx.getStorageSync("userInfo")){
      that.data.userInfo = JSON.parse(wx.getStorageSync("userInfo"));
      if (!that.data.userInfo.guildUser) {
        _this.setData({
          "tempData.isUserIn": false,
        });
        return false;
      }
      _this.setData({
        userInfo: that.data.userInfo
      });
      if (typeof _callBackFun == "function") {
        _callBackFun(that.data.userInfo);
      }
    } else if (that.data.token){
      wx.request({
        url: that.getUrl().getUserInfoUrl,
        method:"POST",
        data: { token: that.data.token},
        success(_data){
          console.log(_data);
          switch (_data.data.message){
            case "OK":
            case "ok":
              that.data.userInfo = _data.data.info;
              wx.setStorage({
                key: 'userInfo',
                data: JSON.stringify(_data.data.info),
              });
              _this.setData({
                userInfo: that.data.userInfo
              });
              if (!_data.data.info.guildUser){
                _this.setData({
                  "tempData.isUserIn":false,
                })
                return false;
              }
              if (typeof _callBackFun == "function"){
                _callBackFun(_data.data.info);
              }
            break;
            default:
              if (parseInt(_data.data.code) == 600){
                
                _this.setData({
                  "tempData.isUserIn": false,
                });
                return false;
              }
              wx.showToast({
                title: "获取用户信息返回错误，请稍后再试！",
                icon: "none",
                duration: 3000
              });
            break;
          }
        }
      })
    }else{
      that.checkJurisdiction(_this);
    }
  },
  // 上传用户微信步数
  updateWeChatStep(_callBackFun){
    let that = this;
    wx.showLoading({
      title: '正在加载',
    });
    wx.getWeRunData({
      success(res){
        wx.request({
          url: that.getUrl().updateStepUrl,
          method:"POST",
          header: { "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},
          data:{
            iv: res.iv,
            session_key:that.data.sessionKey,
            token:that.data.token,
             // token:"KAI",
            decrypt: res.encryptedData
          },
          success(_data){
            console.log(_data);
          },
          complete(){
            if (typeof _callBackFun == "function"){
              _callBackFun();
            }
          }
        });
      },
      fail(){
        if (typeof _callBackFun == "function") {
          _callBackFun();
        }
      },
      complete(){
        wx.hideLoading();
      }
    })
  },
  // 获取部门详情
  getDepartmentInfo(_id,_callBackFun){
    let that = this;
    wx.showLoading({
      title: '正在加载',
    })
    wx.request({
      url: that.getUrl().getDepartmentUrl,
      method:"POST",
      data: { department_id:_id,token:that.data.token},
      success(_data){
        switch (_data.data.message){
          case "OK":
          case "ok":
            if (typeof _callBackFun == "function"){
              _callBackFun(_data.data.info);
            }
          break;
          default:
            wx.showToast({
              title: "获取某部门信息返回错误，请稍后再试！",
              icon: "none",
              duration: 3000
            });
          break;
        }
      },
      complete(){
        wx.hideLoading();
      }
    })
  },
  // 获取某个部门今天的统计数据
  getDepartmentStatistics(_id,startDate,_endDate,_callBackFun){
    let that = this;
    wx.request({
      url: that.getUrl().getDepartmentStatisticsUrl,
      method: "POST",
      data: { department_id: _id, token: that.data.token, start: Math.floor(common.getTimeFromDay(startDate ? startDate : new Date()).startTime / 1000), end: Math.floor(common.getTimeFromDay(_endDate ? _endDate : new Date()).endTime/1000), effective:10000},
      success(_data) {
        console.log(_data);
        switch (_data.data.message){
          case "OK":
          case "ok":
            if (typeof _callBackFun == "function"){
              _callBackFun(_data.data.info);
            }
          break;
        }
      },
    })
  },
// 获取某个人今天的统计数据
  getUserStatistics(_mobile, startDate, _endDate, _callBackFun){
    let that = this;
    wx.request({
      url: that.getUrl().getUserStatisticsUrl,
      method: "POST",
      data: { mobile: _mobile, token: that.data.token, start: Math.floor(common.getTimeFromDay(startDate ? startDate : new Date()).startTime / 1000), end: Math.floor(common.getTimeFromDay(_endDate ? _endDate : new Date()).endTime / 1000), effective: 10000 },
      success(_data) {
        console.log(_data);
        switch (_data.data.message) {
          case "OK":
          case "ok":
            if (typeof _callBackFun == "function") {
              _callBackFun(_data.data.info);
            }
            break;
        }
      },
    })
  },

  // 根据手机号获取某个用户数据信息
  getUserInfoFromPhone(_phone,_callBackFun){
    let that = this;
    wx.request({
      url: that.getUrl().getUserInfoFromPhoneUrl,
      method:"POST",
      data:{
        token:that.data.token,
        mobile: _phone
      },
      success(_data){
        switch (_data.data.message){
          case "OK":
          case "ok":
            if (typeof _callBackFun == "function"){
              _callBackFun(_data.data.info);
            }
          break;
          default:
            wx.showToast({
              title: "根据手机号获取用户信息返回错误，请稍后再试！",
              icon: "none",
              duration: 3000
            });
          break;
        }
      }
    })
  },
  // 获取某个部门的人员排名
  getUserRankListByDepartment(_id,_startDate,__endData,_callBackFun){
    let _this = this;
    wx.request({
      url: _this.getUrl().getUserRankListByDepartmentUrl,
      method:"POST",
      data: { department_id: _id, token: _this.data.token, start: Math.floor(common.getTimeFromDay(_startDate).startTime / 1000), end: Math.floor(common.getTimeFromDay(__endData).endTime / 1000)},
      success(_data){
        switch (_data.data.message){
          case "OK":
          case "ok":
            if (typeof _callBackFun == "function") {
              _callBackFun(_data.data.info);
            }
          break;
          default:

          break;
        }
      }
    })
  },
  //名字中间部分变*
  formatName(name) {
    let newStr;
    if(name.length === 2) {
      newStr = name.substr(0, 1) + '*';
    } else if (name.length > 2) {
      let char = '';
      for (let i = 0, len = name.length - 2; i < len; i++) {
        char += '*';
      }
      newStr = name.substr(0, 1) + char + name.substr(-1, 1);
    } else {
      newStr = name;
    }

    return newStr;
 }

})